package com.dykj.fireFighting.web.controller;

import com.dykj.fireFighting.api.monitoringCenter.entity.PgQuanzhong;
import com.dykj.fireFighting.api.monitoringCenter.entity.PgRegionRecord;
import com.dykj.fireFighting.api.monitoringCenter.entity.PgScoreImport;
import com.dykj.fireFighting.api.monitoringCenter.service.IPgRegionRecordService;
import com.dykj.fireFighting.api.monitoringCenter.vo.PgRegionRecordScoreVo;
import com.dykj.fireFighting.common.core.annotation.AutoLog;
import com.dykj.fireFighting.common.core.api.CommonResult;
import com.dykj.fireFighting.common.core.dto.CommonDto;
import com.dykj.fireFighting.common.core.vo.LoginUserVo;
import com.dykj.fireFighting.common.core.vo.PageVo;
import com.dykj.fireFighting.web.base.shiro.ShiroUtil;
import com.dykj.fireFighting.web.utils.ExportUtils;
import com.dykj.fireFighting.web.utils.PgRegionRecordScoreVoTreeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.jxls.common.Context;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.XLSReader;
import org.jxls.transform.poi.PoiTransformer;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.*;


/**
 * 接口
 *
 * @Author JacksonTu
 * @Date 2022-02-16 10:17:27
 */
@Slf4j
@Api(value = "接口", tags = {"接口"})
@RestController
@RequestMapping("pgRegionRecord")
public class PgRegionRecordController {

    @DubboReference
    private IPgRegionRecordService pgRegionRecordService;


    /**
     * 列表
     *
     * @return
     */
    @AutoLog(value = "-分页列表查询")
    @ApiOperation(value = "分页列表", notes = "分页列表")
    @GetMapping("/list")
//    @RequiresPermissions("pgRegionRecord/list")
    public CommonResult<PageVo<PgRegionRecord>> treeGrid(CommonDto commonDto) {
        PageVo<PgRegionRecord> page = pgRegionRecordService.pageList(commonDto);
        return CommonResult.success(page);
    }

    /**
     * 获取信息
     */
    @AutoLog(value = "-获取信息")
    @ApiOperation(value = "获取信息", notes = "获取信息")
    @ApiImplicitParam(paramType = "path", name = "id", value = "主键ID", dataType = "String", required = true)
    @GetMapping("/info/{id}")
//    @RequiresPermissions("pgRegionRecord/info")
    public CommonResult<PgRegionRecord> info(@PathVariable("id") String id) {
        PgRegionRecord pgRegionRecord = pgRegionRecordService.getById(id);
        return CommonResult.success(pgRegionRecord);
    }

    /**
     * 保存信息
     */
    @AutoLog(value = "-保存信息")
    @ApiOperation(value = "保存信息", notes = "保存信息")
    @PostMapping("/save")
//    @RequiresPermissions("pgRegionRecord/save")
    public CommonResult save(@Valid @RequestBody PgRegionRecord pgRegionRecord) {
        try {
            pgRegionRecord.setCreateBy(ShiroUtil.getUser().getName());
            pgRegionRecord.setCreateTime(new Date());
            pgRegionRecordService.save(pgRegionRecord);
            return CommonResult.success("添加成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }

    /**
     * 修改信息
     */
    @AutoLog(value = "-修改信息")
    @ApiOperation(value = "修改信息", notes = "修改信息")
    @PostMapping("/update")
//    @RequiresPermissions("pgRegionRecord/update")
    public CommonResult update(@Valid @RequestBody PgRegionRecord pgRegionRecord) {
        try {

            pgRegionRecordService.updateById(pgRegionRecord);
            return CommonResult.success("修改成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }

    /**
     * 删除信息
     */
    @AutoLog(value = "-删除信息")
    @ApiOperation(value = "删除信息", notes = "删除信息")
    @ApiImplicitParam(paramType = "query", name = "ids", value = "ID数组", dataType = "String", required = true, allowMultiple = true)
    @PostMapping("/delete")
//    @RequiresPermissions("pgRegionRecord/delete")
    public CommonResult delete(@RequestBody String[] ids) {
        try {
            pgRegionRecordService.removeByIds(Arrays.asList(ids));
            return CommonResult.success("删除成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }


    @PostMapping("/import")
    //@RequiresPermissions("fireInformation/import")
    public CommonResult importDevice(@RequestParam("file") MultipartFile file, @RequestParam("regionRecordId") String regionRecordId, RedirectAttributes redirectAttributes) {
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
            return CommonResult.failed("请上传文件");
        }
        String fileName = file.getOriginalFilename();
        if (!fileName.endsWith(".xls") && !fileName.endsWith(".xlsx") && !fileName.endsWith(".xlsm")) {
            redirectAttributes.addFlashAttribute("message", "Please select a correct file to upload");
            return CommonResult.failed("文件格式错误");
        }
        LoginUserVo user = ShiroUtil.getUser();
        String xmlConfig = "uploadXml/score.xml";
        try (InputStream xmlInputStream = getClass().getClassLoader().getResourceAsStream(xmlConfig)) {
            XLSReader reader = ReaderBuilder.buildFromXML(xmlInputStream);
            try (InputStream xlsInputStream = new BufferedInputStream(file.getInputStream())) {
                List<PgScoreImport> scoreList = new ArrayList<>();
                Map<String, Object> beans = new HashMap<>();
                beans.put("scoreList", scoreList);
                List<PgQuanzhong> qz2 = new ArrayList<>();
                List<PgQuanzhong> qz1 = new ArrayList<>();
                beans.put("qz2", qz2);
                beans.put("qz1", qz1);
                reader.read(xlsInputStream, beans);
                Map<String, Object> params = new HashMap<>();
                params.put("scoreList", scoreList);
                params.put("regionRecordId", regionRecordId);
                params.put("user", user);
                params.put("qz2", qz2);
                params.put("qz1", qz1);
                int i = pgRegionRecordService.importScore(params);
                return CommonResult.success("导入完成");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("导入失败，请检查上传的文件信息");
        }
    }

    /**
     * 导出
     *
     * @param regionId
     * @param response
     * @throws Exception
     */
    @GetMapping("/download")
    public void download(String regionId, HttpServletResponse response) throws Exception {
        //获取所有数据
        List<PgRegionRecordScoreVo> pgRegionRecordScoreVoList = pgRegionRecordService.getPgRegionRecordScoreList(regionId);
        //获取下级条数
        List<PgRegionRecordScoreVo> pgRegionRecordScoreVoNumList = pgRegionRecordService.getpgRegionRecordScoreVoNumList(regionId);
        //行合并计算
        int sum = 0;
        for (PgRegionRecordScoreVo pprs : pgRegionRecordScoreVoList) {
            if (pprs.getLevel() == 0 || pprs.getLevel() == 1) {
                int total = 0;
                for (PgRegionRecordScoreVo pprsn : pgRegionRecordScoreVoNumList) {
                    if (pprs.getLevel() == 0 && pprs.getId().equals(pprsn.getParentId())) {
                        total += pprsn.getTotal();
                        pprs.setTotal(total);
                    } else if (pprs.getLevel() == 1 && pprs.getId().equals(pprsn.getId())) {
                        pprs.setTotal(pprsn.getTotal());
                        sum += pprsn.getTotal();
                    }
                }
            }
        }

        PgRegionRecordScoreVoTreeUtil pgRegionRecordScoreVoTreeUtil = new PgRegionRecordScoreVoTreeUtil(pgRegionRecordScoreVoList);
        List<PgRegionRecordScoreVo> tabList = pgRegionRecordScoreVoTreeUtil.buildTree();

        PgRegionRecordScoreVo pgRegionRecordScoreVo = new PgRegionRecordScoreVo();
        pgRegionRecordScoreVo.setName("城市消防安全");
        pgRegionRecordScoreVo.setTotal(sum);
        pgRegionRecordScoreVo.setChildList(tabList);

        Context initialContext = PoiTransformer.createInitialContext();
        initialContext.putVar("tabList", tabList);
        initialContext.putVar("pgRegionRecordScoreVo", pgRegionRecordScoreVo);
        ExportUtils.exportExcel(initialContext, "pgRegionRecordScore.xlsx", "基本指标评价结果汇总.xlsx", response);

    }

}
